package inbound_invoice

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type InboundInvoiceSummaryLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInboundInvoiceSummaryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InboundInvoiceSummaryLogic {
	return &InboundInvoiceSummaryLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InboundInvoiceSummaryLogic) InboundInvoiceSummary() (resp *types.InboundInvoiceSummaryResponse, err error) {
	resp = new(types.InboundInvoiceSummaryResponse)
	//1.查询所有含税入库单
	stockins, err := l.svcCtx.StockInModel.FindByPage(l.ctx, fmt.Sprintf(" where has_tax=1"))
	switch err {
	case nil:
	case model.ErrNotFound:
		resp.Code = http.StatusNoContent
		resp.Msg = "成功"
		return resp, nil
	default:
		fmt.Printf("[Error]查询含税入库单:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.汇总发票金额
	for _, one := range stockins {
		resp.Data.Total += one.Total
		resp.Data.TotalTax += one.Total / 100 * float64(one.Tax)
	}

	//3.查询已开发票
	invoices, err := l.svcCtx.InboundInvoiceModel.FindByPage(l.ctx, "")
	switch err {
	case nil, model.ErrNotFound:
	default:
		fmt.Printf("[Error]查询已开发票:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//4.汇总已开票金额
	for _, one := range invoices {
		resp.Data.Used += one.Total
		resp.Data.UsedTax += one.Total / 100 * float64(one.Tax)
	}
	resp.Data.Available = resp.Data.Total - resp.Data.Used
	resp.Data.AvailableTax = resp.Data.TotalTax - resp.Data.UsedTax

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
